package com.bby.screentool.vm;

import static com.bby.screentool.service.ScreenCaptureService.ACTION_STOP;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.projection.MediaProjection;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.bby.screentool.base.RecordStatus;
import com.bby.screentool.event.Action;
import com.bby.screentool.event.ScreenModelObserver;
import com.bby.screentool.model.ScreenModel;
import com.bby.screentool.service.ScreenCaptureService;

import org.webrtc.PeerConnection;
import org.webrtc.ScreenCapturerAndroid;

public class ScreenRecorderViewModel extends AndroidViewModel implements ServiceConnection, ScreenModelObserver {
    private final String TAG = getClass().getName();
    private Intent projectionResultData;
    private final ScreenModel model = new ScreenModel(this.getApplication(), this);
    private final MutableLiveData<RecordStatus> recordStatus = new MutableLiveData<>(RecordStatus.UNAVAILABLE);

    private final MutableLiveData<Boolean> audioRecording = new MutableLiveData<>(false);
    private final MutableLiveData<Boolean> audioShow = new MutableLiveData<>(false);
    private final MutableLiveData<String> screenId = new MutableLiveData<>("加载中...");
    private final MutableLiveData<Event> event = new MutableLiveData<>();
    private final MutableLiveData<String> toast = new MutableLiveData<>();
    private final MutableLiveData<String> statusText = new MutableLiveData<>();

    //在service中注册一个广播接收器，用于接收关闭service的广播
    private final BroadcastReceiver stopReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_STOP.equals(intent.getAction())) {
                if (isRecording()) {
                    toggleRecording();
                }
            }
        }
    };

    public ScreenRecorderViewModel(@NonNull Application application) {
        super(application);
        initEvent();
    }

    private void initEvent() {
        getApplication().getApplicationContext().registerReceiver(stopReceiver, new IntentFilter(ACTION_STOP));
    }

    public void receiveClick() {

    }

    public void toggleAudioRecording() {
        // 正在播放
        boolean res = false;
        if (Boolean.TRUE.equals(audioRecording.getValue())) {
            // 关闭
            res = model.stopAudioRecord();
        } else {
            // 打开
            res = model.startAudioRecord();
        }
        if (res) {
            audioRecording.postValue(Boolean.FALSE.equals(audioRecording.getValue()));
        } else {
            toast.postValue("连接已断开！");
        }
    }

    public void toggleRecording() {
        if (isRecording()) {
            getApplication().unbindService(this);
            Intent stopIntent = new Intent(getApplication(), ScreenCaptureService.class);
            stopIntent.putExtra("stop", true);
            getApplication().startService(stopIntent);

            model.releaseRecording(getApplication());
            recordStatus.postValue(RecordStatus.STOP);
            event.postValue(Event.STOP_LOCAL_VIEW);
            audioShow.postValue(false);
        } else {
            if (projectionResultData == null) {
                event.postValue(Event.ASK_PROJECTION);
                return;
            }
            Intent intent = new Intent(getApplication(), ScreenCaptureService.class);
            intent.putExtra("data", projectionResultData);
            getApplication().bindService(intent, this, Context.BIND_AUTO_CREATE);
            getApplication().startForegroundService(intent);
            recordStatus.postValue(RecordStatus.RUNNING);
            audioShow.postValue(true);
        }
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        model.readyRecord(getApplication(), new ScreenCapturerAndroid(projectionResultData, new MediaProjection.Callback() {
        }));
        event.postValue(Event.START_LOCAL_VIEW);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    }

    @Override
    public void onMessageShow(String msg) {
        toast.postValue(msg);
    }

    @Override
    public void onAsk(Action action) {
        String from = action.getFrom();
        statusText.postValue(from + "连接中...");
        model.sendOffer(from);
    }

    @Override
    public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) {
        Log.i(TAG, "连接状态改变：" + iceConnectionState.name());
    }

    public enum Event {
        ASK_PROJECTION,
        STOP_LOCAL_VIEW,
        START_LOCAL_VIEW
    }

    public void setProjectionResultData(Intent projectionResultData) {
        this.projectionResultData = projectionResultData;
    }

    public ScreenModel getModel() {
        return model;
    }

    public Intent getProjectionResultData() {
        return projectionResultData;
    }

    public MutableLiveData<String> getScreenId() {
        return screenId;
    }

    public MutableLiveData<Event> getEvent() {
        return event;
    }

    public MutableLiveData<String> getToast() {
        return toast;
    }

    public MutableLiveData<RecordStatus> getRecordStatus() {
        return recordStatus;
    }

    public MutableLiveData<Boolean> getAudioRecording() {
        return audioRecording;
    }

    public MutableLiveData<Boolean> getAudioShow() {
        return audioShow;
    }

    public MutableLiveData<String> getStatusText() {
        return statusText;
    }

    public boolean isRecording() {
        return recordStatus.getValue() == RecordStatus.RUNNING;
    }

}
